<template>
    <page-meta :page-style="$theme.pageStyle">
        <!-- #ifndef H5 -->
        <navigation-bar :front-color="$theme.navColor" :background-color="$theme.navBgColor" />
        <!-- #endif -->
    </page-meta>
    <view class="index" :style="pageStyle">
        <!-- 将 header 放置在固定位置 -->
        <view class="custom-header" :style="{ 'padding-top': statusBarHeight + 'px' }">
            <text class="header-text">资质</text>
        </view>
        <view class="custom-body" :style="{ 'margin-top': statusBarHeight + 'px' }">
            <u-form :model="model" :rules="rules" ref="formRef" label-width="300">
                <view class="card-title" :style="cardBackgroundStyle">身份信息</view>
                <view class="form-container">
                    <u-form-item label="司机姓名" prop="name">
                        <u-input
                            class="right-placeholder"
                            v-model="model.name"
                            placeholder="请输入姓名"
                        />
                    </u-form-item>
                    <u-form-item label="手机号" prop="phone">
                        <u-input
                            class="right-placeholder"
                            v-model="model.phone"
                            placeholder="请输入手机号"
                        />
                    </u-form-item>
                    <u-form-item label="身份证号" prop="id_card">
                        <u-input
                            class="right-placeholder"
                            v-model="model.id_card"
                            placeholder="请输入身份证号"
                        />
                    </u-form-item>
                    <u-form-item
                        label="网络预约出租汽车驾驶员证"
                        prop="network_license_pic"
                        :label-position="'top'"
                    >
                        <custom-upload
                            v-model:current-url="model.network_license_pic"
                            :file-list="carImageFileList"
                            :maxCount="1"
                            @success="handleSuccess('network_license_pic', $event)"
                        />
                    </u-form-item>
                </view>
                <view class="card-title" :style="cardBackgroundStyle">车辆信息</view>
                <view class="form-container">
                    <u-form-item label="运营车型" prop="car_type_id">
                        <u-input
                            class="right-placeholder"
                            v-model="selectCarTypeLabel"
                            type="select"
                            placeholder="请选择运营车型"
                            @click="selectCarType.show = true"
                        />
                    </u-form-item>
                    <u-form-item label="车型" prop="vehicle_model">
                        <u-input
                            class="right-placeholder"
                            v-model="model.vehicle_model"
                            placeholder="请输入车品牌及车型"
                        />
                    </u-form-item>
                    <u-form-item label="车牌号" prop="license_plate">
                        <code-input
                            :maxLength="8"
                            mode="box"
                            @finish="handleFinish"
                            @click="toggleLicenseKeyboard"
                        />
                    </u-form-item>
                    <u-form-item label="车辆颜色" prop="color">
                        <u-input
                            class="right-placeholder"
                            v-model="model.color"
                            placeholder="请输入车辆颜色"
                        />
                    </u-form-item>
                    <u-form-item label="车辆颜色" prop="color">
                        <u-input
                            class="right-placeholder"
                            v-model="model.color"
                            placeholder="请输入车辆颜色"
                        />
                    </u-form-item>

                    <u-form-item label="车架号" prop="frame_number">
                        <u-input
                            class="right-placeholder"
                            v-model="model.frame_number"
                            placeholder="请输入车架号"
                        />
                    </u-form-item>

                    <u-form-item label="行车本" prop="vehicle_license_pic" :label-position="'top'">
                        <custom-upload
                            v-model:current-url="model.vehicle_license_pic"
                            :file-list="carImageFileList"
                            :maxCount="1"
                            @success="handleSuccess('vehicle_license_pic', $event)"
                        />
                    </u-form-item>
                    <u-form-item label="驾照" prop="driver_license_pic" :label-position="'top'">
                        <custom-upload
                            v-model:current-url="model.driver_license_pic"
                            :file-list="carImageFileList"
                            :maxCount="1"
                            @success="handleSuccess('driver_license_pic', $event)"
                        />
                    </u-form-item>
                    <u-form-item
                        label="网络预约出租汽车运输证"
                        prop="network_licensee_pic"
                        :label-position="'top'"
                    >
                        <custom-upload
                            v-model:current-url="model.network_licensee_pic"
                            :file-list="carImageFileList"
                            :maxCount="1"
                            @success="handleSuccess('network_licensee_pic', $event)"
                        />
                    </u-form-item>
                    <u-form-item label="车辆图片" :label-position="'top'">
                        <u-row>
                            <u-col span="6" style="padding: 0">
                                <custom-upload
                                    v-model:current-url="model.car_image_front"
                                    :file-list="carImageFileList"
                                    :maxCount="1"
                                    @success="handleSuccess('car_image_front', $event)"
                                />
                                <text class="upload-tip"> *车正面带拍照的照片</text>
                            </u-col>
                            <u-col span="6">
                                <custom-upload
                                    v-model:current-url="model.car_image_interior"
                                    :file-list="carImageFileList"
                                    :maxCount="1"
                                    @success="handleSuccess('car_image_interior', $event)"
                                />
                                <text class="upload-tip"> *车前排照片</text>
                            </u-col>
                            <u-col span="6">
                                <custom-upload
                                    v-model:current-url="model.car_image_rear"
                                    :file-list="carImageFileList"
                                    :maxCount="1"
                                    @success="handleSuccess('car_image_rear', $event)"
                                />
                                <text class="upload-tip"> *车后排照片</text>
                            </u-col>
                        </u-row>
                    </u-form-item>
                </view>
                <button class="submit-btn button" @click="submitForm" :loading="submitting">
                    {{ submitting ? '提交中...' : '提交审核' }}
                </button>
            </u-form>
            <u-select
                v-model="selectCarType.show"
                :list="carTypeList"
                :label-name="'name'"
                :value-name="'id'"
                :border="false"
                :placeholder="'请选择车型'"
                @confirm="handleCarTypeChange"
            />
            <!-- 车牌键盘 -->
            <u-keyboard
                v-model="showLicenseKeyboard.show"
                :mode="'car'"
                @change="handleLicenseChange"
            />
        </view>
        <!-- 返回顶部按钮 -->
        <u-back-top
            :scroll-top="scrollTop"
            :top="100"
            :customStyle="{
                backgroundColor: '#FFF',
                color: '#000',
                boxShadow: '0px 3px 6px rgba(0, 0, 0, 0.1)'
            }"
        >
        </u-back-top>

        <!--  #ifdef MP  -->
        <!--  微信小程序隐私弹窗  -->
        <MpPrivacyPopup></MpPrivacyPopup>
        <!--  #endif  -->

        <tabbar />
    </view>
</template>

<script setup lang="ts">
import { getIndex } from '@/api/shop'
import { onLoad, onPageScroll, onReady } from '@dcloudio/uni-app'
import { computed, reactive, ref } from 'vue'
import { useAppStore } from '@/stores/app'
import { useUserStore } from '@/stores/user'
import { submitDriverInfo } from '@/api/user'
import { carTypeAll } from '@/api/car_type'
import CustomUpload from '@/components/custom-upload/custom-upload.vue'
import CodeInput from '@/components/code-input/code-input.vue'
// #ifdef MP
import MpPrivacyPopup from './component/mp-privacy-popup.vue'
import CarKeyboard from '@/components/car-keyboard/car-keyboard.vue'
import UKeyboard from '@/uni_modules/vk-uview-ui/components/u-keyboard/u-keyboard.vue'
// #endif
const carImageFileList = ref([])
const formRef = ref(null)
const appStore = useAppStore()
const userStore = useUserStore()
const state = reactive<{
    pages: any[]
    meta: any[]
    article: any
}>({
    pages: [],
    meta: [],
    article: null
})
const model = reactive({
    user_id: userStore.userInfo.id,
    name: '',
    phone: '',
    id_card: '',
    car_type_id: null as number | null, // 明确类型
    vehicle_model: '',
    licensePlate: '',
    car_number: '',
    frame_number: '',
    car_image_front: '',
    car_image_interior: '',
    car_image_rear: '',
    driver_license_pic: '',
    vehicle_license_pic: '',
    network_license_pic: '',
    network_licensee_pic: ''
})

const carTypeList = ref([])
const submitting = ref(false)
const selectCarType = reactive({
    show: false,
    current: {} as any
})

const selectCarTypeLabel = ref('')
const getCarType = async () => {
    try {
        const data = await carTypeAll()
        carTypeList.value = data
        if (carTypeList.value.length > 0) {
            model.car_type_id = carTypeList.value[0].id
            selectCarType.current = carTypeList.value[0]
            selectCarTypeLabel.value = carTypeList.value[0].name
        } else {
            uni.showToast({ title: '暂无车型数据', icon: 'none' })
        }
    } catch (error) {
        uni.showToast({ title: '车型加载失败', icon: 'none' })
        console.error('获取车型失败:', error)
    }
}

const rules = reactive({
    name: [{ required: true, message: '请输入司机姓名' }],
    phone: [
        { required: true, message: '请输入手机号' },
        { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确' }
    ],
    id_card: [
        { required: true, message: '请输入身份证号' },
        { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '身份证号格式不正确' }
    ],
    license_plate: [{ required: true, message: '请输入车牌号' }],
    car_type_id: [{ required: true, message: '请选择车型' }],
    vehicle_model: [{ required: true, message: '请输入车辆型号' }],
    frame_number: [{ required: true, message: '请输入车架号' }],
    driver_license_pic: [{ required: true, message: '请上传驾照' }],
    vehicle_license_pic: [{ required: true, message: '请上传行车本' }],
    network_license_pic: [{ required: true, message: '请上传网络预约出租汽车驾驶员证' }],
    network_licensee_pic: [{ required: true, message: '请上传网络预约出租汽车运输证' }],
    car_image_front: [{ required: true, message: '请上传车正面带车牌的照片' }],
    car_image_interior: [{ required: true, message: '请上传车前排照片' }],
    car_image_rear: [{ required: true, message: '请上传车后排照片' }]
})
const scrollTop = ref<number>(0)
const percent = ref<number>(0)
const statusBarHeight = ref<number>(0)

// 根页面样式
const pageStyle = computed(() => {
    return { 'background-color': `#FFFFFF` }
})

const getData = async () => {
    try {
        const data = await getIndex()
        if (data && data?.page?.data && data?.page?.meta) {
            state.pages = JSON.parse(data.page.data)
            state.meta = JSON.parse(data.page.meta)
            state.article = data.article
            uni.setNavigationBarTitle({
                title: state.meta[0]?.content?.title || '资质认证'
            })
        } else {
            uni.showToast({ title: '页面数据加载异常', icon: 'none' })
        }
    } catch (error) {
        uni.showToast({ title: '页面数据加载失败', icon: 'none' })
    }
}

const cardBackgroundStyle = computed(() => {
    const bg = appStore.getStyleConfig.cardBg
    return {
        'background-image': `url(${bg})`,
        'background-repeat': 'no-repeat',
        'background-position': 'left',
        'background-size': '80px auto',
        width: '100px'
    }
})
let lastScrollTime = 0
onPageScroll((event: any) => {
    // 添加节流处理
    if (Date.now() - lastScrollTime < 100) return
    scrollTop.value = event.scrollTop
    const top = uni.upx2px(100)
    percent.value = event.scrollTop / top > 1 ? 1 : event.scrollTop / top
    lastScrollTime = Date.now()
})

const handleSuccess = (field: string, res: any[]) => {
    if (res.length > 0) {
        model[field] = JSON.stringify(res)
    } else {
        uni.showToast({ title: '图片上传失败', icon: 'none' })
        console.error('上传错误:', res)
    }
}

const handleCarTypeChange = (value: any) => {
    if (!value || value.length === 0) return

    const selected = value[0]
    model.car_type_id = selected.id

    selectCarType.current = selected
    selectCarTypeLabel.value = selected.label // ✅ 可以正常赋值
}

const showLicenseKeyboard = ref(false)
// 使用函数封装点击事件
const toggleLicenseKeyboard = () => {
    console.log('点击了车牌号输入框')
    showLicenseKeyboard.value = true
}
// 当键盘值变化时更新输入框内容
const onCarKeyboardChange = (val: string) => {
    model.license_plate = val
    showLicenseKeyboard.value = false
}
// 确认时关闭键盘
const handleFinish = () => {
    showLicenseKeyboard.value = true
}
const submitForm = async () => {
    if (submitting.value) return
    try {
        submitting.value = true

        const isValid = await formRef.value.validate()

        if (isValid) {
            const res = await submitDriverInfo(model)
            uni.showToast({ title: '提交成功', icon: 'success' })
        }
    } catch (error) {
        uni.showToast({ title: '请检查表单内容', icon: 'none' })
    } finally {
        submitting.value = false
    }
}
onReady(() => {
    formRef.value.setRules(rules)
})
onLoad(() => {
    try {
        const systemInfo = uni.getSystemInfoSync()
        statusBarHeight.value = systemInfo.statusBarHeight + 8
        uni.showLoading({ title: '加载中' })
        Promise.all([getData(), getCarType()]).finally(() => {
            uni.hideLoading()
        })
    } catch (error) {
        uni.showToast({ title: '页面初始化失败', icon: 'none' })
        console.error('页面初始化错误:', error)
    }
})
</script>

<style lang="scss" scoped>
.index {
    position: relative;
    background-repeat: no-repeat;
    background-size: 100% auto;
    overflow: hidden;
    width: 100%;
    transition: all 1s;
    min-height: calc(100vh - env(safe-area-inset-bottom));
    margin-top: 44px; /* 与 custom-header 的高度保持一致 */
}

.custom-header {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    //background-color: #f8f8f8; /* 背景色可根据主题调整 */
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 999; /* 确保在其他内容之上 */
    //box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* 添加阴影提升视觉层次 */
}

.header-text {
    font-size: 20px;
    text-align: center;
}

.custom-body {
    background: #f8f8f8;
    padding: 15px;
}

.card-title {
    font-size: 20px;
    font-weight: bold;
    height: 45px;
    background-size: auto;
}

.form-container {
    background-color: #ffffff;
    padding: 16px;
    border-radius: 8px;
    margin: 10px 0;
}

.submit-btn {
    margin-bottom: 120rpx;
}

.right-placeholder {
    :deep(.u-input__input) {
        text-align: right;
    }
}

.upload-tip {
    display: block;
    margin-top: 4px;
    font-size: 14px;
    text-align: center;
    color: #f6a22d;
}
</style>
